package com.sugar.psych.assessment.module.business.service.studentauth;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sugar.psych.assessment.module.business.dal.dataobject.school.SchoolDO;
import com.sugar.psych.assessment.module.business.dal.dataobject.user.UserDO;
import com.sugar.psych.assessment.module.business.dal.mysql.school.SchoolMapper;
import com.sugar.psych.assessment.module.business.dal.mysql.user.BizUserMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import com.sugar.psych.assessment.module.business.controller.admin.studentauth.vo.*;
import com.sugar.psych.assessment.module.business.dal.dataobject.studentauth.StudentAuthDO;
import com.sugar.psych.assessment.framework.common.pojo.PageResult;
import com.sugar.psych.assessment.framework.common.pojo.PageParam;
import com.sugar.psych.assessment.framework.common.util.object.BeanUtils;

import com.sugar.psych.assessment.module.business.dal.mysql.studentauth.StudentAuthMapper;
import org.springframework.web.multipart.MultipartFile;

import static com.sugar.psych.assessment.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.sugar.psych.assessment.framework.common.util.collection.CollectionUtils.convertList;
import static com.sugar.psych.assessment.framework.common.util.collection.CollectionUtils.diffList;
import static com.sugar.psych.assessment.module.business.enums.ErrorCodeConstants.*;

/**
 * 学生认证信息 Service 实现类
 *
 * @author Ysugar
 */
@Service
@Validated
public class StudentAuthServiceImpl implements StudentAuthService {

    @Resource
    private StudentAuthMapper studentAuthMapper;
    @Resource
    private SchoolMapper schoolMapper;
    @Resource
    private BizUserMapper userMapper;

    @Override
    public Long createStudentAuth(StudentAuthSaveReqVO createReqVO) {
        // 插入
        StudentAuthDO studentAuth = BeanUtils.toBean(createReqVO, StudentAuthDO.class);
        studentAuthMapper.insert(studentAuth);
        // 返回
        return studentAuth.getId();
    }

    @Override
    public void updateStudentAuth(StudentAuthSaveReqVO updateReqVO) {
        // 校验存在
        validateStudentAuthExists(updateReqVO.getId());
        // 更新
        StudentAuthDO updateObj = BeanUtils.toBean(updateReqVO, StudentAuthDO.class);
        studentAuthMapper.updateById(updateObj);
    }

    @Override
    public void deleteStudentAuth(Long id) {
        // 校验存在
        validateStudentAuthExists(id);
        // 删除
        studentAuthMapper.deleteById(id);
    }

    @Override
        public void deleteStudentAuthListByIds(List<Long> ids) {
        // 校验存在
        validateStudentAuthExists(ids);
        // 删除
        studentAuthMapper.deleteByIds(ids);
        }

    private void validateStudentAuthExists(List<Long> ids) {
        List<StudentAuthDO> list = studentAuthMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(STUDENT_AUTH_NOT_EXISTS);
        }
    }

    private void validateStudentAuthExists(Long id) {
        if (studentAuthMapper.selectById(id) == null) {
            throw exception(STUDENT_AUTH_NOT_EXISTS);
        }
    }

    @Override
    public StudentAuthDO getStudentAuth(Long id) {
        return studentAuthMapper.selectById(id);
    }

    @Override
    public PageResult<StudentAuthRespVO> getStudentAuthPage(StudentAuthPageReqVO pageReqVO) {
        return studentAuthMapper.selectPage(pageReqVO);
    }

    @Override
    public void importExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), new ReadListener<Map<Integer, String>>() {
            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                for (int i = 0; i < 4; i++) {
                    StudentAuthDO studentAuth = new StudentAuthDO();
                    studentAuth.setAuthName(data.get(0));
                    studentAuth.setAuthId(data.get(1));

                    // 查询学校信息
                    SchoolDO schoolDO = schoolMapper.selectOne(SchoolDO::getName, data.get(2));
                    if (schoolDO != null){
                        studentAuth.setSchoolId(schoolDO.getId());
                        // 查询是否重复
                        Long count = studentAuthMapper.selectCount(Wrappers.<StudentAuthDO>lambdaQuery()
                                .eq(StudentAuthDO::getAuthName, studentAuth.getAuthName())
                                .eq(StudentAuthDO::getAuthId, studentAuth.getAuthId())
                                .eq(StudentAuthDO::getSchoolId, studentAuth.getSchoolId()));
                        if (count == 0)
                            studentAuthMapper.insert(studentAuth);
                    }
                }
            }

            // 读取完毕
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {}
        }).sheet().doRead();
    }

}